﻿using System;
using System.IO;
using System.Management.Automation;
using Microsoft.SharePoint.Administration;
using SharePoint.ImportExport.Core;
using SharePoint.ImportExport.Importer;


namespace SPMigrationCmdlets
{
    [Cmdlet(VerbsData.Import, "SPMigrationData")]
    public class Importer : PSCmdlet
    {
        private bool allowImportToExistingLibraries = false;
        private bool allowImportToExistingSites = false;
        private string directoryName;
        private string url;
        private bool setSecurity = true;
        private string siteDefinitionName = String.Empty;
        private string owner = String.Empty;
        private string contact = String.Empty;

        [Parameter(Mandatory = true)]
        public string DirectoryName
        {
            get { return this.directoryName; }
            set { this.directoryName = value; }
        }

        [Parameter(Mandatory = true)]
        public string Url
        {
            get { return this.url; }
            set { this.url = value; }
        }

        [Parameter(Mandatory = false)]
        public SwitchParameter SetSecurity
        {
            get { return this.setSecurity; }
            set { this.setSecurity = value; }
        }

        [Parameter(Mandatory = false)]
        public SwitchParameter AllowImportToExistingSites
        {
            get { return this.allowImportToExistingSites; }
            set { this.allowImportToExistingSites = value; }
        }

        [Parameter(Mandatory = false)]
        public SwitchParameter AllowImportToExistingLibraries
        {
            get { return this.allowImportToExistingLibraries; }
            set { this.allowImportToExistingLibraries = value; }
        }

        [Parameter(Mandatory = false)]
        public string SiteDefinitionName
        {
            get { return this.siteDefinitionName; }
            set { this.siteDefinitionName = value; }
        }

        [Parameter(Mandatory = false)]
        public string Owner
        {
            get { return this.owner; }
            set { this.owner = value; }
        }

        [Parameter(Mandatory = false)]
        public string Contact
        {
            get { return this.contact; }
            set { this.contact = value; }
        }


        protected override void ProcessRecord()
        {
#if DEBUG
            System.Diagnostics.Debug.Assert(false);
#endif
            Uri uri = new Uri(this.Url);

            string WebApplicationUrl = uri.AbsoluteUri.Replace(uri.AbsolutePath, string.Empty);
            string ManagedPath = string.Empty;
            string SiteName = string.Empty;
            SPWebApplication spwebApp = SPWebApplication.Lookup(new Uri(WebApplicationUrl));
            foreach (SPPrefix spmanagedPath in spwebApp.Prefixes)
            {
                if (spmanagedPath.Name.Length > 0)
                {
                    if (uri.AbsolutePath.StartsWith("/" + spmanagedPath.Name))
                    {
                        ManagedPath = spmanagedPath.Name;
                        break;
                    }
                }
            }

            if (ManagedPath.Length > 1)
            {
                SiteName = uri.AbsolutePath.Substring(2 + ManagedPath.Length);
            }
            else
            {
                if (uri.AbsolutePath.Length > 1)
                {
                    SiteName = uri.AbsolutePath.Substring(1);
                }
            }


            ImportWrapper importer = new ImportWrapper();
            Logger.Init(DirectoryName + "\\import" + DateTime.Now.ToString("MMddHHmm") + ".log", ErrorLevel.Information);
            WriteVerbose("Log file: " + DirectoryName + "\\import" + DateTime.Now.ToString("MMddHHmm") + ".log");
            Logger.LogDataSendingEvent += new Logger.LogDataEventHandler(IncomingEventLogData);
            bool Bypass = true;
            if (importer.Init(true))
            {
                string s = string.Empty;
                if (File.Exists(DirectoryName + "\\firstrun.txt"))
                {
                    s = File.ReadAllText(DirectoryName + "\\firstrun.txt");
                }
                else
                {
                    Bypass = false;
                }

                if (!Bypass)
                {
                    importer.Process(DirectoryName, WebApplicationUrl, AllowImportToExistingSites, AllowImportToExistingLibraries, SetSecurity, true, ManagedPath, SiteName, SiteDefinitionName, Owner, Contact, out s);
                    File.WriteAllText(DirectoryName + "\\firstrun.txt", s);
                    Logger.Close();
                    Logger.Init("import" + DateTime.Now.ToString("MMddHHmm") + ".log", ErrorLevel.Information);
                }

                ContentDeploymentInfo cdi = new ContentDeploymentInfo();
                if (cdi.ReadFromString(s))
                {
                    importer.ImportData(cdi, DirectoryName, Url, true, true, "ImportData.log");
                    File.Delete(DirectoryName + "\\firstrun.txt");
                }
                Logger.Close();
                Logger.LogDataSendingEvent -= new Logger.LogDataEventHandler(IncomingEventLogData);


            }

        }

        private void IncomingEventLogData(object sender, SPEventArgs e)
        {
            string message = e.Message;
            if (message.StartsWith("Warning-"))
            {
                message = message.Replace("Warning-", "");
                WriteWarning(message);
            }
            else if (message.StartsWith("Error-"))
            {
                message = message.Replace("Error-", "");
                ErrorRecord er = new ErrorRecord(new Exception(message.Replace("Error-", "")), "SPMIGER001", ErrorCategory.InvalidOperation, null);
                WriteError(er);
                return;
            }
            else
            {
                message = message.Replace("Information-", "");
                message = message.Replace("Progress-", "");
                string logArgs = DateTime.Now.ToLongTimeString() + "  " + message;
                WriteVerbose(logArgs);
                WriteCommandDetail(logArgs);
            }
        }
    }


}
